package com.tongzhan.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tongzhan.entity.User;
import com.tongzhan.repository.UserRepository;
import com.tongzhan.util.HttpClient;
import com.tongzhan.util.JwtUtil;
import com.tongzhan.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class LoginController {

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.secret}")
    private String secret;

    @Value("${weixin.url}")
    private String weixinurl;

    @Autowired
    private UserRepository userRepository;

    /**
     * 小程序端登录接口
     *
     * @param response 响应
     * @param username 用户名
     * @param password 密码
     * @param openid   openid
     * @return Result
     */
    @PostMapping("/login")
    public Result login(HttpServletResponse response, String username, String password, String openid) {
        if (StringUtils.isEmpty(openid)) {
            return new Result(Result.FAIL, "参数缺失");
        }
        //返回数据
        Map<String, Object> info = new HashMap<>();
        //用户信息
        User user;
        if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
            Query query = new Query();
            query.addCriteria(Criteria.where("IsDelete").is(0));
            query.addCriteria(Criteria.where("UserName").is(username.trim())
                    .and("PassWord").is(password.trim()));//密码前端MD5加密后传入
            //查询用户信息
            user = userRepository.findOne(query);
            if (user == null) {
                return new Result(Result.FAIL, "用户名或密码错误");
            }
            user.setAppkey(openid);
            user.setUpdateTime(LocalDateTime.now());
            userRepository.updateByPrimaryKey(user);
        } else {
            //微信登录
            Query query = new Query();
            query.with(Sort.by(Sort.Direction.DESC, "UpdateTime"));
            user = userRepository.findOne(query.addCriteria(Criteria.where("Appkey").is(openid).and("IsDelete").is(0)));
            if (user == null) {
                return new Result(Result.FAIL, "用户不存在");
            }
        }
        //生成jwt令牌,返回到客户端
        info.put("userInfo", user);
        //基于工具类生成jwt令牌
//        String token = JwtUtil.createJWT(UUID.randomUUID().toString(), user.getUserId(), null);
        String token = JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(user), null);
        //将token放在响应头
        response.setHeader(JwtUtil.AUTH_HEADER_KEY, token);
        info.put("token", token);
        return new Result(Result.SUCCESS, "请求成功", info);
    }

    private String getAccessToken(String code) {
        //授权类型，此处只需填写 authorization_code
        String grant_type = "authorization_code";
        String url = weixinurl + "?appid=" + appid + "&secret=" + secret + "&grant_type=" + grant_type + "&js_code=" + code;
        String doGet = HttpClient.doGet(url);
        JSONObject object = JSONObject.parseObject(doGet);
        if (object != null && object.containsKey("openid")) {
            return object.getString("openid");
        }
        return null;
    }

    /**
     * 判断用户是否第一次进入小程序接口
     *
     * @param code code
     * @return Return
     */
    @PostMapping("/isFirstLogin")
    public Result getTest(String code) {
        //openid
        String openid = getAccessToken(code);
        if (StringUtils.isNotEmpty(openid)) {
            User user = userRepository.findOne(new Query().addCriteria(Criteria.where("Appkey").is(openid).and("IsDelete").is(0)));
            if (user == null) {
                return new Result("301", "是", openid);
            }
        }
        return new Result(Result.SUCCESS, "否", openid);
    }

    @PostMapping("/manageLogin")
    public Result manageLogin(String username, String password) {
        //用户信息
        User user = null;
        if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
            Query query = new Query();
            query.addCriteria(Criteria.where("IsDelete").is(0));
            query.addCriteria(Criteria.where("UserName").is(username.trim())
                    .and("PassWord").is(password.trim()));//密码前端MD5加密后传入
            //查询用户信息
            user = userRepository.findOne(query);
            if (user == null) {
                return new Result(Result.FAIL, "用户名或密码错误");
            }
        }
        return new Result(Result.SUCCESS, "请求成功", user);
    }
}